package com.g2room.sort;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.g2room.utils.StringUtil;

public class DicSort {
	/**
	 * 对传入参数进行排序（sign参数不参与排序和加密），然后MD5加密，如传入参数为：<br>
	 * //http://account.carry6.com/bill/add?gold=12&uid=23&appid=guess
	 * 		&timestamp=345566724537812&sign=d091ce94d5cc13f651559ea17b68d5d3<br>
	 * 则排序后字符串为：<br>
	 * 	appid=guess&gold=12&timestamp=345566724537812&uid=23<br>
	 * 加密后返回的字符串为：<br>
	 * 		d091ce94d5cc13f651559ea17b68d5d3
	 * 
	 * @param map
	 * @return
	 */
	public static String encryption(Map<String, Object> map) {
		String ciphertext = "";
		List<String> keys = new ArrayList<String>();
		for(String key : map.keySet()) {
			if(key.equalsIgnoreCase("sign")) continue;
			keys.add(key);
		}
		// 对参数键进行排序
		Collections.sort(keys);
		StringBuffer plaintext = new StringBuffer();
		for(String key : keys) {
			if(plaintext.length() > 1) {
				plaintext.append("&");
			}
			plaintext.append(key);
			plaintext.append("=");
			plaintext.append(map.get(key));
		}
		ciphertext = StringUtil.md5(plaintext.toString());
		return ciphertext;
	}

	public static void main(String[] args) {
		Map<String, Object> param = new HashMap<String, Object>();
		//http://account.carry6.com/bill/add?gold=12&uid=23&appid=guess&timestamp=345566724537812&sign=7af5a405633c9c58cea1ce1d20b2c319
		param.put("gold", 12);
		param.put("uid", 23);
		param.put("appid", "guess");
		param.put("timestamp", 345566724537812l);
		param.put("sign", "d091ce94d5cc13f651559ea17b68d5d3");
		System.out.println("===" + encryption(param));
	}
}